const express = require("express");
const apiRouter = express.Router();
const fs = require("fs");
const writeData = require("../db/module/writeData");
const readData = require("../db/module/readData");
const delData = require("../db/module/delData");
const jwt = require("jsonwebtoken");
const secretKey = "Aa2317770710"; //生成token的密钥

// 文件上传中间件

// 获取所有用户列表
apiRouter.post("/userList", async (req, res) => {
  // 获取到客户端通过查询字符串发送到服务器的数据
  try {
    const params = req.body;


    let result = await readData(params, "userList");
    res.send(result);
  } catch (error) {
    res.send({
      code: 50000,
      msg: error,
    });
  }
});

// 新增用户信息接口
apiRouter.post("/addUserInfo", async (req, res) => {
  try {
    const params = req.body;
    let createTime = params.createTime
      ? params.createTime
      : new Date().toLocaleString();

    params.createTime = createTime;

    let userJurisdiction = [
      { name: "超级管理员", value: "1" },
      { name: "管理员", value: "2" },
      { name: "普通用户", value: "3" },
    ];

    params.roleName = userJurisdiction.filter(
      (item) => item.value == params.roleCode
    )[0].name;

    let result = await writeData(params, "userList");

    res.send(result);
  } catch (error) {
    res.send({
      code: 50000,
      msg: error,
    });
  }
});

// 删除用户
apiRouter.post("/deleteUser", async (req, res) => {
  try {
    const params = req.body;
    result;


    let result = await delData(params, "userList");

    res.send(result);
  } catch (error) {
    res.send({
      code: 50000,
      msg: error,
    });
  }
});

// 登录接口
apiRouter.post("/login", async (req, res) => {
  try {
    // 获取到客户端通过查询字符串发送到服务器的数据
    const query = req.body;

    if (!query.accountNumber) {
      res.send({
        code: 50000,
        msg: "用户名不能为空！！",
      });
    }

    // 查询数据库是否存在当前数据;
    let result = await readData(query, "userList", true);

    let parmse = { ...result.data };


    const payload = { ...query };

    // token配置选项
    const options = {
      expiresIn: "1h", // 1小时后过期
    };

    if (result.data.id) {
      // 记录当前用户登录时间
      let date = new Date().toLocaleString();
      result.data.lastLoginTime = date;

      // 更改数据库最近一次登录时间的状态
      await writeData(result.data, "userList");

      // 获取token 并且返回给前端
      jwt.sign(payload, secretKey, options, (err, token) => {
        if (err) {
          throw err;
        }

        res.send({
          code: 20000,
          data: {
            avatar:
              "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
            introduction: "I am a super administrator",
            name: parmse.roleName,
            roles: ["admin"],
            token: token,
            id: parmse.id,
          },
        });
      });
    } else {
      res.send({
        code: 50000,
        msg: "账号或密码错误",
      });
    }
  } catch (error) {
    res.send({
      code: 50000,
      msg: "未找到数据库或其他原因：" + error,
    });
  }
});

module.exports = apiRouter;
